(function () {
	init()

	$("#addcard").on('click', function() {
		window.location.href = 'regist.html'
	})


	
})()

function init () {
	var cardlist = []

	var wecode = getQueryString('code') || ''
	if(wecode === ''){
		wecode = localStorage.getItem('wecode') || ''
	}

	var openID = localStorage.getItem('openID') || ''

    if (wecode === '') {
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3a06c113295b44c3&redirect_uri=http%3a%2f%2f' + encodeURIComponent(window.location.href.substr(7)) + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'  //'https://healthcarddemo.tengmed.com/index.php?c=healthcard&a=login'
	} else if (openID === '') {
		localStorage.setItem("wecode",wecode)
		//获取OpenID，暂存。
		$.ajax({
			url: 'http://healthcard.jkgly.cn/api/jkgly/getOpenId?code=' + wecode, 
			dataType: 'json',
			type: 'get',
			success: function (res) {
				if (res.openid) {
					localStorage.setItem('openID', res.openid),
					openID = res.openid
				} else if (res.errcode) {
					alert(res.errmsg)
				}
				//清理wecode，防止出错。
				localStorage.removeItem('wecode')
			},
			error: function (res){
				alert(res)
			}
		})
	} else if (openID != '') {
		//获取OpenID成功后，调用接口，回去CardList
		$.ajax({
			url:'http://healthcard.jkgly.cn/api/jkgly/getHealthCardByOpenId?openId=' + openID,	//获取电子健康卡列表API接口--待完成
			type: 'get',
			dataType: 'json',
			success: function (resp) {
				if(resp.retcode === 0) {
					cardlist = resp.cardlist
					buildcardlist(cardlist)

					//解析二维码
					for(var i=0; i<cardlist.length; i++){
						jQuery(".qrcode" + i).qrcode({
							width : "158",               //二维码的宽度
							height : "158",
							render: "canvas",
							text: cardlist[i].qrCodeText,
							background: "#ffffff",       //二维码的后景色
							foreground: "#000000",        //二维码的前景色
							src: 'img/logo_.png'             //二维码中间的图片
						}); 
					}

				}else if(resp.retcode === 1) {
					window.location.href = resp.redirect_uri
				}
			}
		})
	}
	
	
	
	
	
	/* else {
		var qrCodeText = getQueryString('qrCodeText') || ''
		var name = getQueryString('name') || ''
		var idCard = getQueryString('idCard') || ''
		var phone = getQueryString('phone') || ''

		if (qrCodeText === '') {}
		else
		{
			cardlist = [{"idCard": idCard,"name": name,"phone": phone,"qrCodeText": qrCodeText}]
			buildcardlist(cardlist)
			jQuery(".qrcode").qrcode({
				width : "162",               //二维码的宽度
				height : "162",
				render: "canvas",
				text: qrCodeText,
				background: "#ffffff",       //二维码的后景色
				foreground: "#000000",        //二维码的前景色
				src: 'img/logo_.png'             //二维码中间的图片
			}); 
		}
	} */

	

	/* $.ajax({
		url:'https://healthcarddemo.tengmed.com/index.php?c=healthcard&a=getHealthCardList',	//获取电子健康卡列表API接口--待完成
		type: 'get',
		dataType: 'json',
		success: function (resp) {
			if(resp.retcode === 0) {
				cardlist = resp.cards
				buildcardlist(cardlist)
			}else if(resp.retcode === 302) {
				window.location.href = resp.redirect_uri
			}
		}
	}) */
}

function buildcardlist (list) {
	var length = 0
	var listhtml = ''
	if(list.length > 5) {
		length = 5
		$("#addcard").hide()
	} else {
		length = list.length

		$("#tips").html('您还可以办理' + (5 - list.length) + '张卡')
	}

	if (length === 0) {

		// let binded = getCookie('bindhealthcard')
		// if (!binded) {
		// 	window.location.href = 'https://healthcarddemo.tengmed.com/index.php?c=healthcard&a=authhealthCode'
		// 	setCookie('bindhealthcard', true)
		// }

		listhtml = '<div class="emptycard"><img src="img/nocard.png"/><p>暂无健康卡</p></div>'
	} else {
		for(var i = 0; i < length; i++) {
/* 			listhtml = listhtml + '<a href="personal.html?openID=' + localStorage.getItem('openID') + '&name=' + list[i].name + 
					'&idCard=' + list[i].idNumber + '&qrCodeText=' + list[i].qrCodeText + '&phone=' + list[i].phone1 +
					'" class="card">' +
					'<p class="name" id="name">' + list[i].name + '</p>' +
					'<p class="num" id="idcard">' + list[i].idNumber + '</p>' +
					'<div class="qrcode qrcode' + i + '">' +
					'</div>' +
				'</a>' */

			listhtml = listhtml + '<a href="personal.html?openID=' + localStorage.getItem('openID') + '&name=' + list[i].name +
				'&idCard=' + list[i].idNumber + '&qrCodeText=' + list[i].qrCodeText + '&phone=' + list[i].phone1 +
				'" class="card">' +
				'<p class="wyh">山东省卫生健康委员会</p>' +
				'<div class="info">'+
				'<p class="name" id="name">' + list[i].name + '</p>' +
				'<p class="num" id="idcard">' + list[i].idNumber + '</p>' +
				'</div>' +
				'<div class="qrcode qrcode' + i + '">' +
				'</div>' +
			'</a>'
		}
	}
	
	$("#cardlist").html(listhtml)
}

//获取url参数
function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 匹配目标参数
  var result = window.location.search.substr(1).match(reg); // 对querystring匹配目标参数
  if (result != null) {
    return decodeURIComponent(result[2]);
  } else {
    return null;
  }
}

//设置cookie
function setCookie(c_name,value,expiredays) {
	var exdate = new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name + "=" + escape(value) +
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

//获取Cookie
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) {
                c_end = document.cookie.length
            }
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}
